package hk.linkcredit.walletservice.wallet.service.strategy;

import hk.linkcredit.walletservice.constant.Status;
import hk.linkcredit.walletservice.constant.WalletConstants;
import hk.linkcredit.walletservice.exception.BizException;
import hk.linkcredit.walletservice.utils.StringUtils;
import hk.linkcredit.walletservice.wallet.domain.entity.WalletOrder;
import hk.linkcredit.walletservice.wallet.domain.vo.WalletOrderReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: Jamnsin
 * @Date: 2022/6/12 16:26
 */
@Slf4j
@Component(WalletConstants.WALLET_ORDER_STATUS_4)
public class OrderFailuerStrategy extends OrderStatusService implements OrderStatusStrategy {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealWalletOrder(WalletOrderReq walletOrderReq) {
        log.info("开始处理钱包订单状态 >>> orderStatus = {}, walletOrderReq = {}", WalletConstants.WALLET_ORDER_STATUS_FAILUER, walletOrderReq);

        if (!isRepayOrder(walletOrderReq.getOrderType())) {
            WalletOrder walletOrder = this.getWalletOrder(walletOrderReq.getCustNo(), walletOrderReq.getOrderSerialNo());
            doWalletOrder(walletOrderReq, walletOrder);
            return;
        }

        List<WalletOrder> walletOrders = this.getWalletOrders(walletOrderReq.getCustNo(), walletOrderReq.getOrderSerialNo());
        walletOrders.forEach(walletOrder -> {
            doWalletOrder(walletOrderReq, walletOrder);
        });
    }

    private void doWalletOrder(WalletOrderReq walletOrderReq, WalletOrder walletOrder) {
        if (this.checkCustNo(walletOrderReq.getCustNo(), walletOrder.getCustNo())) {
            log.error("订单客户号与传参客户号不一致");
            return;
        }

        log.info("当前订单状态：currentStatus = {}，targetStatus = {}", walletOrder.getOrderStatus(), WalletConstants.WALLET_ORDER_STATUS_FAILUER);
        if (StringUtils.equalsAny(walletOrder.getOrderStatus(), WalletConstants.WALLET_ORDER_STATUS_SUCCESS, WalletConstants.WALLET_ORDER_STATUS_FAILUER)) {
            throw new BizException(Status.WALLET_ORDER_STATUS_EXPIRED);
        }

        this.updateWalletOrder(walletOrder.getId(), WalletConstants.WALLET_ORDER_STATUS_FAILUER, walletOrderReq.getMessage());

        this.unfreezeWalletAmount(walletOrder);
    }
}
